#!/bin/bash
time=$(date +%Y"."%m"."%d" "%k":"%M":"%S);
year=$(date +%Y);
month=$(date +%m);
day=$(date +%d);
hour=$(date +%k);
backupdir=/var/backup/svn_bak
# ======================== fun getTime  ========================
function getTime(){
    echo $(date +%Y"-"%m"-"%d" "%k":"%M":"%S);
}
# ======================== logFile ========================
logPath=/var/backup/log

if [ ! -d "$logPath" ]
then
    mkdir $logPath;
fi

logFile="/var/backup/log/backup_svn_${year}${month}.log";

if [ ! -f "$logFile" ]
then
    touch $logFile;
fi

echo $(getTime) svn files backup command excute starting.....  >> $logFile;

# ========================  fun checkBackupFile ========================
function checkBackupFile(){
        echo $(getTime) backup file  $1 checking... >> $logFile;
        if [ ! -f "$1"  ];
        then
                echo $(getTime) $1 is not exits, will be created later... >> $logFile;
        else
                echo $(getTime) $1 is old, will be overwrited. >> $logFile;
                rm -rf $1;
        fi
}
# ========================  fun checkTmpFileBefore ========================
function checkTmpFileBefore(){
        echo $(getTime) tmp file $1 checking before compress ... >> $logFile;
        if [ ! -f "$1"  ];
        then
                echo $(getTime) "$1" is not exits, state OK. >> $logFile;
        else
                echo $(getTime) $1 is already exits, will be deleted. >> $logFile;
                rm -rf $1;
        fi
}
# ========================  fun checkTmpFileAfter ========================
function checkTmpFileAfter(){
        echo $(getTime) svnfiles compress completed! >> $logFile
        echo $(getTime) tmp file $1 checking after compress ... >> $logFile
        if [ ! -f "$1"  ]; then
                echo $(getTime) $1 is not exits,compress failed!  >> $logFile
        else
                echo $(getTime) $1 is exits, state OK, compress success! prepare move to nas. >> $logFile
                if [ ! -d "$backupdir/" ]; then
                        echo $(getTime) ERROR!! $backupdir IS NOT FOUND!,it seems network ERROR. >> $logFile
                else
                        mv $1 "$backupdir/"
                        if [ ! -f "$backupdir/$1"  ]; then
                                echo $(getTime) ERROR! move to nas failed! >> $logFile
                        else
                                echo $(getTime) $1 movo to nas success!! >> $logFile
                        fi
                fi
        fi
}

tmpfile_svn=/tmp/backup_svn.$(date +%Y"-"%m).tar.bz2
bakfile_svn=$backupdir/backup_svn.$(date +%Y-%m).tar.bz2
checkTmpFileBefore "$tmpfile_svn";
tar -jpc -f $tmpfile_svn /var3/svn
checkBackupFile "$bakfile_svn";
checkTmpFileAfter "$tmpfile_svn";
